#include "util.hpp"
#include <functional>
#include <vector>

using func_t = std::function<void()>;

#define INIT(v) do{\
    v.push_back(printLog);\
    v.push_back(downLoad);\
    v.push_back(upLoad);\
}while(0)

#define EXEC_TASK(v) do{\
    for(const auto& cb : v) cb();\
}while(0)

void printLog()
{
    std::cout << "这是一条日志" << std::endl;
}
void downLoad()
{
    std::cout << "这是下载" << std::endl;
}
void upLoad()
{
    std::cout << "这是上传" << std::endl;
}

int main()
{
    std::vector<func_t> callbacks;
    INIT(callbacks);

    setNonBlock(0);// 设置文件描述符0为非阻塞式IO

    char buffer[1024];
    while(true)
    {
        // 提示符
        printf(">> ");
        fflush(stdout);

        ssize_t s = read(0, buffer, sizeof(buffer) - 1);// 当字符串读取
        if(s > 0)
        {
            buffer[s - 1/* 最后一个字符是'\n' */] = 0;// 当作字符串
            std::cout << "echo: " << buffer << std::endl;
        }
        else if(s == 0)
        {
            std::cout << "had read end" << std::endl;
            break;
        }
        else
        {
            // todo
            // std::cout << "s: " << s << " error: " << strerror(errno) << std::endl;
            // std::cout << "EAGAIN: " << EAGAIN << "  EWOULDBLOCK: " << EWOULDBLOCK << std::endl;

            // raed函数底层没有数据时，返回EAGAIN
            if(errno == EAGAIN)
            {
                std::cout << "数据未就绪" << std::endl;
                // 未出错时，才可以做其他事
                EXEC_TASK(callbacks);
            }
            // 读取被信号中断
            else if(errno == EINTR)
            {
                continue;
            }
            else
            {
                std::cout << "s: " << s << " error: " << strerror(errno) << std::endl;
                break;
            }
        }

        sleep(1);
    }

    return 0;
}